package com.pactera.demo.base.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.demo.base.dto.RoleResource;
import com.pactera.demo.base.dto.RoleBindDto;
import com.pactera.demo.base.dto.RoleDto;
import com.pactera.demo.base.entity.Role;
import com.pactera.demo.base.service.IRoleService;
import com.pactera.demo.common.dto.ResponseResult;
import com.pactera.demo.common.enums.StatusCodeEnum;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色定义表 前端控制器
 * </p>
 *
 * @author mybatis.plus
 * @since 2020-02-27
 */
@RestController
@RequestMapping("/base")
public class RoleController {

    private IRoleService roleService;

    @PostMapping("/role")
    public ResponseResult create(@RequestBody @Valid RoleDto roleDto, BindingResult result){

        if(result.hasErrors()){
            List<String> errors = result.getAllErrors().stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.toList());
            return ResponseResult.fail(StatusCodeEnum.ILLEGAL_PARAM, errors);
        }

        Role role = new Role();
        role.setRoleName(roleDto.getRoleName());
        role.setRoleCode(roleDto.getRoleCode());
        role.setComments(roleDto.getComments());
        this.roleService.save(role);
        return ResponseResult.success();
    }

    @GetMapping("/role/{size}/{index}")
    public ResponseResult list(@PathVariable("size") int size,@PathVariable("index") int index){
        IPage<Role> page = this.roleService.page(new Page<>(index, size));
        return ResponseResult.success(page);
    }

    @PostMapping("/role/bind")
    public ResponseResult bind(@RequestBody RoleBindDto roleBindDto,BindingResult result){
        if(result.hasErrors()){
            List<String> errors = result.getAllErrors().stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.toList());
            return ResponseResult.fail(StatusCodeEnum.ILLEGAL_PARAM, errors);
        }
        List<String> resourceIds = roleBindDto.getResourceIds();
        List<RoleResource> roleResources = resourceIds.stream().map(x -> new RoleResource(roleBindDto.getRoleId(), x)).collect(Collectors.toList());
        this.roleService.bindResourcesToRole(roleResources);
        return ResponseResult.success();
    }


    public RoleController(IRoleService roleService) {
        this.roleService = roleService;
    }
}

